package cn.com.guage.dynamic.datasource.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import cn.com.guage.dynamic.datasource.annotation.ChoiceDataSource;
import cn.com.guage.dynamic.datasource.config.DatasourceContextHolder;

/**
 * aop 拦截注解
 *
* @author yangdechao
 * @version 1.0
 * @date 2020/07/13 15:19
 */
@Aspect
@Component
public class DynamicDataSourceAspect {
	
    private final static Logger logger = LoggerFactory.getLogger(DatasourceContextHolder.class);

	/**
	 * 方法执行之前获取方法上面的注解
	 * @param joinPoint
	 */
    //@Before("@annotation(cn.com.guage.dynamic.datasource.annotation.ChoiceDataSource)")
    @Before("execution(* cn.com.guage.dynamic.datasource.service.impl..*.*(..))")
    public void beforeSwitchDS(JoinPoint joinPoint) {
    	logger.info("DynamicDataSourceAspect---------beforeSwitchDS----开始");
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		Method method = methodSignature.getMethod();
		Boolean isClassPresent = method.getDeclaringClass().isAnnotationPresent(ChoiceDataSource.class);
		String dataSource = DatasourceContextHolder.DEFAULT_DATASOURCE;
		//注解是否在类上
    	logger.info("注解是否在类上："+isClassPresent);
		if(isClassPresent) {
			dataSource = method.getDeclaringClass().getAnnotation(ChoiceDataSource.class).value();
		}
		logger.info("注解是否在方法上："+method.isAnnotationPresent(ChoiceDataSource.class));
		// 注释RoutingDataSource是否在方法上。如果在则返回true；不在则返回false
		if (method.isAnnotationPresent(ChoiceDataSource.class)) {
			ChoiceDataSource routingDataSource = method.getDeclaredAnnotation(ChoiceDataSource.class);
			dataSource = routingDataSource.value();
		}
		DatasourceContextHolder.setDB(dataSource);
		logger.info("DynamicDataSourceAspect---------beforeSwitchDS----结束");
    }

    /**
     * 方法使用完后，要清空DatasourceContextHolder
     */
    //@After("@annotation(cn.com.guage.dynamic.datasource.annotation.ChoiceDataSource)")
    @Before("execution(* cn.com.guage.dynamic.datasource.service.impl..*.*(..))")
    public void afterSwitchDS() {
    	logger.info("DynamicDataSourceAspect---------afterSwitchDS----开始");
        DatasourceContextHolder.clearDB();
    	logger.info("DynamicDataSourceAspect---------afterSwitchDS----结束");

    }
}